package importTable.jsch;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.FileWriter;
import java.io.InputStream;

public class JschThread extends Thread {
    String cmd;
    String hostname;
    String userName;
    String password;

    public JschThread(String cmd, String hostname, String userName, String password) {
        this.cmd = cmd;
        this.hostname = hostname;
        this.userName = userName;
        this.password = password;
    }

    @Override
    public void run() {
        super.run();
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(userName, hostname, 22);
            session.setPassword(password);
            session.setUserInfo(new MyUserInfo());
            session.setConfig("StrictHostKeyChecking", "no");

            session.connect(30000);   // making a connection with timeout.

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);

            channel.setInputStream(null);

            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();

            channel.connect();

            byte[] tmp = new byte[1024];
            String line = "";
            FileWriter fw = new FileWriter(Thread.currentThread().getName() + ".txt");
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    line = new String(tmp, 0, i);
                    System.out.print(line);
                    fw.write(line + "\n");
                    fw.flush();
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: " + channel.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            fw.close();
            channel.disconnect();
            session.disconnect();
            System.out.println("关闭了");
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}
